package org.my.spring.agent.mcp.playwright.controller;

import com.alibaba.fastjson2.JSONObject;
import com.microsoft.playwright.Browser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.my.spring.agent.common.domain.Result;
import org.my.spring.agent.mcp.core.config.AgentPlaywrightConfig;
import org.my.spring.agent.mcp.core.domain.dto.IntentResult;
import org.my.spring.agent.mcp.core.domain.enums.BroswerEnum;
import org.my.spring.agent.mcp.core.utils.PlaywrightUtil;
import org.my.spring.agent.mcp.playwright.service.AutoWebMcpService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Playwright自动化控制接口
 * 提供基于大模型意图识别结果的Web自动化操作能力
 * 支持页面导航、元素点击、文本输入和结果提取等浏览器操作
 */
@RestController
@RequiredArgsConstructor
@CrossOrigin
@RequestMapping("/agent")
@Slf4j
public class PlaywrightAgentController {
    private final AgentPlaywrightConfig playwrightConfig;
    private final AutoWebMcpService autoWebMcpService;

    /**
     * Web自动化任务执行接口
     * 接收大模型意图识别结果，解析并执行一系列浏览器自动化步骤
     * 若用户首次使用，自动初始化浏览器实例并缓存
     *
     * @param jsonObject 包含意图识别结果的JSON对象，需符合IntentResult结构
     * @return 执行结果，成功时返回操作结果或提取的页面内容
     */
    @PostMapping("/auto/web")
    public Result<?> todoWeb(@RequestBody JSONObject jsonObject) {
        IntentResult intentResult = jsonObject.to(IntentResult.class);
        if (!PlaywrightUtil.hasCacheBrowser(intentResult.userId())) {
            Browser browser = PlaywrightUtil.initBrowser(PlaywrightUtil.getBrowserModel(playwrightConfig, BroswerEnum.CHROME.getName()));
            browser.newContext();
            PlaywrightUtil.addCacheBrowser(intentResult.userId(), browser);
        }
        List<IntentResult.Step> stepList = intentResult.steps();
        if (ObjectUtils.isEmpty(stepList)) {
            return Result.error("请输入步骤");
        }
        for (IntentResult.Step step : stepList) {
            IntentResult.Command command = step.command();
            String action = command.action();
            if ("navigate".equals(action)) {
                Result<String> result = autoWebMcpService.navigate(intentResult.userId(), command);
                if (Result.isError(result)) {
                    return result;
                }
            } else if ("clickElement".equals(action)) {
                Result<String> result = autoWebMcpService.clickElement(intentResult.userId(), command);
                if (Result.isError(result)) {
                    return result;
                }
            } else if ("inputText".equals(action)) {
                Result<String> result = autoWebMcpService.inputText(intentResult.userId(), command);
                if (Result.isError(result)) {
                    return result;
                }
            } else if ("outputStr".equals(action)) {
                return autoWebMcpService.outputStr(intentResult.userId(), command);
            }
        }

        return Result.success();
    }
}

